package nciae.db.utils;


import org.apache.pdfbox.rendering.PDFRenderer;


import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class DocumentConverterUtils {

    // 默认图片格式
    private static final String IMAGE_FORMAT = "png";


    private final LocalOfficeManager officeManager;

    // 定义线程池（4 个并发线程）
    private final ExecutorService executorService;

//    @PostConstruct
//    public void init() {
//        // 初始化线程池
//        executorService = Executors.newFixedThreadPool(4);
//    }

    @Autowired
    public DocumentConverterUtils(LocalOfficeManager officeManager) {
        this.officeManager = officeManager;
        this.executorService = Executors.newFixedThreadPool(4);
    }

    /**
     * 将文档（pdf, ppt, pptx, doc, docx）转换成 PDF
     *
     * @param inputPath  输入文件路径
     * @param outputPath 输出 PDF 文件路径
     */
    public void convertToPdf(String inputPath, String outputPath) {

        File inputFile = new File(inputPath);
        File outputFile = new File(outputPath);

        try {
            LocalConverter.make(officeManager)
                    .convert(inputFile)
                    .to(outputFile)
                    .execute();

            System.out.println("转换成功：" + outputFile.getAbsolutePath());
        } catch (Exception e) {
            System.err.println("转换失败：" + e.getMessage());
        }

    }

    /**
     * 将 PDF 的每一页转换成图片
     *
     * @param pdfPath   PDF 文件路径
     * @param outputDir 输出目录路径
     */
    public void convertPdfToImages(String pdfPath, String outputDir) {

        try {
            File pdfFile = new File(pdfPath);
            File outputDirectory = new File(outputDir);

            if (!outputDirectory.exists()) {
                System.out.println(outputDirectory.mkdirs());
            }

            try (PDDocument document = PDDocument.load(pdfFile)) {
                PDFRenderer renderer = new PDFRenderer(document);
                for (int i = 0; i < document.getNumberOfPages(); i++) {
                    // 使用300 DPI 生成高清图片
                    BufferedImage image = renderer.renderImageWithDPI(i, 100);
                    File outputFile = new File(outputDirectory, "page_" + (i + 1) + "." + IMAGE_FORMAT);
                    ImageIO.write(image, IMAGE_FORMAT, outputFile);
                }
            }
        } catch (IOException e) {
            System.err.println("图片生成失败：" + e.getMessage());
        }

    }

    /**
     * 将文档直接转换为图片（先转 PDF 再转图片）
     *
     * @param inputPath 输入文件路径
     * @param outputDir 输出目录路径
     */
    public void convertDocumentToImages(String inputPath, String outputDir) {

        try {

            executorService.submit(() ->{
                // 生成 PDF 文件路径
                String pdfPath = outputDir + File.separator + new File(inputPath).getName() + ".pdf";

                // 将文档转换为 PDF
                convertToPdf(inputPath, pdfPath);
                System.out.println("转为pdf");

                // 将 PDF 转成图片
                convertPdfToImages(pdfPath, outputDir);

                // 删除中间生成的 PDF 文件（可选）
                System.out.println(new File(pdfPath).delete());
            });

        } catch (Exception e) {
            System.err.println("转换失败：" + e.getMessage());
        }

    }
}
